package next.Functionality;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import next.TemplateActivity.R;


public class NetworkingFunctionality extends EmailFunctionality {
	
	//--Variables--
	protected ImageView img;
	protected String txt;
	//EXAMPLES:
	//"http://cornellchinesetennis.files.wordpress.com/2009/06/roger-federer-with-nsix-one-tour.jpg"
	//"http://www.streetcar.org/mim/cable/images/cable-01.jpg"
	//"http://www.appleinsider.com/appleinsider.rss"
	
	
	public ImageView DownloadImageURL(String url)
	{
		if (url!=null){
		//--download image on asynchronous task--
		new ImgBackgroundTask().execute(url);
		return img;
		}else {
			Log.d("Error Downloading Image", "Null URL");
			return null;
		}
	}
	
	public String DownloadFileRSS (String url)
	{
		if (url!=null){
		// ---download an RSS feed---
		new TextBackgroundTask().execute(url);
		return txt;
		}
		else {
			Log.d("Error Downloading File RSS", "Null URL");
			return null;
		}
		
	}


	/** This class is intended to execute asynchronous tasks.*/
	private class ImgBackgroundTask extends AsyncTask<String, Void, Bitmap> {
		
		protected Bitmap doInBackground(String... url) {
			// ---download an image---
			Bitmap bitmap = DownloadImage(url[0]);
			return bitmap;
		}

		protected void onPostExecute(Bitmap bitmap) {
			img = (ImageView) findViewById(R.id.test_V_IV1);
			img.setImageBitmap(bitmap);
		}
	}
	
	/** This class is intended to execute asynchronous tasks.*/
	private class TextBackgroundTask extends AsyncTask<String, Void, String> {
		
		protected String doInBackground(String... url) {
			// ---download text---
			txt = DownloadText(url[0]);
			return txt;
		}

		protected void onPostExecute(String doc) {
			Toast.makeText(getBaseContext(), doc, Toast.LENGTH_LONG).show();
		}
	}


	/** This method open a HTTP connection.*/
	private InputStream OpenHttpConnection(String urlString) throws IOException {
		InputStream in = null;
		int response = -1;
		URL url = new URL(urlString);
		URLConnection conn = url.openConnection();
		if (!(conn instanceof HttpURLConnection))
			throw new IOException("Not an HTTP connection");
		try {
			HttpURLConnection httpConn = (HttpURLConnection) conn;
			httpConn.setAllowUserInteraction(false);
			httpConn.setInstanceFollowRedirects(true);
			httpConn.setRequestMethod("GET");
			// Toast.makeText(this, "NES", Toast.LENGTH_LONG).show();
			response = httpConn.getResponseCode();
			httpConn.connect();
			if (response == HttpURLConnection.HTTP_OK) {
				in = httpConn.getInputStream();
			}
		} catch (Exception ex) {
			throw new IOException("Error connecting");
		}
		return in;
	}

	/** This method download an image through HTTP connection. */
	private Bitmap DownloadImage(String URL) {
		Bitmap bitmap = null;
		InputStream in = null;
		try {
			in = OpenHttpConnection(URL);
			bitmap = BitmapFactory.decodeStream(in);
			in.close();
		} catch (IOException e1) {
			Toast.makeText(this, e1.getLocalizedMessage(), Toast.LENGTH_LONG)
					.show();
			e1.printStackTrace();
		}
		return bitmap;
	}

	/** This method download s .RSS through a HTTP connection.*/
	private String DownloadText(String URL) {
		int BUFFER_SIZE = 2000;
		InputStream in = null;
		try {
			in = OpenHttpConnection(URL);
		} catch (IOException e1) {
			Toast.makeText(this, e1.getLocalizedMessage(), Toast.LENGTH_LONG)
					.show();
			e1.printStackTrace();
			return "";
		}
		InputStreamReader isr = new InputStreamReader(in);
		int charRead;
		String str = "";
		char[] inputBuffer = new char[BUFFER_SIZE];
		try {
			while ((charRead = isr.read(inputBuffer)) > 0) {
				// ---convert the chars to a String---
				String readString = String
						.copyValueOf(inputBuffer, 0, charRead);
				str += readString;
				inputBuffer = new char[BUFFER_SIZE];
			}
			in.close();
		} catch (IOException e) {
			Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_LONG)
					.show();
			e.printStackTrace();
			return "";
		}
		return str;
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.generic_test_layout);
		
	}

}
